<template>
  <div>
    <el-tooltip placement="top"
                :open-delay="1000">
      <div slot="content">{{$t('custom.nextTicket.templatelist')}}</div>
      <el-select v-model="currentTemplateId"
                 style="width: 220px"
                 clearable
                 @change="changeTemplate"
                 ref="templateSelect">
        <div style="padding: 0 20px"
             v-if="$attrs.page !== 'nextTicketSetting'">
          <div @click="add" v-if="$route.path!=='/nextTicket'&& $hasPermission('sys:settings:add-new-filter')"
               style="margin:4px auto 10px;cursor: pointer ;width:285px;height:28px;color:#17B3A3;background-color: #138dc71a;border:1px dashed #17B3A3;border-radius:4px;text-algin:center;line-height:28px"
               >
            <div class="add_new_filter" 
                 style="display:flex;justify-content:center">
              <i class="cuifont icon_add_square"
                 style="color:#17B3A3;font-size:14px;font-weight:400">Add New Template</i>
            </div>
          </div>
        </div>
        <el-option v-for="(item) in templateOptions"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id">
          <div  v-if="$route.path!=='/nextTicket'">
            <span style="float: left">{{ item.name }}</span>
            <el-button class="optionButton"
                       v-if="item.id && $hasPermission('sys:settings:delete-next-ticket-filter')"
                       size='mini'
                       type="text"
                       @click.stop='deleteTemplate(item)'>
              <i class="cuifont icon_delete"></i>
            </el-button>
            <el-button class="optionButton"
                       size='mini'
                       type="text"
                       v-else><i style="visibility: hidden"
                 class="cuifont icon_delete"></i></el-button>
            <el-button v-if="$attrs.page !== 'nextTicketSetting' && $hasPermission('sys:settings:copy-next-ticket-filter')"
                       class="optionButton"
                       size='mini'
                       type="text"
                       @click.stop='clone(item)'>
              <i class="cuifont icon_copy optionIcon"></i>
            </el-button>
            <el-button v-if="$attrs.page !== 'nextTicketSetting'&& $hasPermission('sys:settings:edit-filter-dialog')"
                       class="optionButton"
                       style="margin-left: 0"
                       size='mini'
                       type="text"
                       @click.stop='change(item)'>
              <i class="cuifont icon_edit optionIcon"></i>
            </el-button>
            <el-button v-if="$attrs.page === 'nextTicketSetting'&&item.id &&$hasPermission('sys:settings:edit-filter-dialog')"
                       class="optionButton"
                       style="margin-left: 0"
                       size='mini'
                       type="text"
                       @click.stop='changeName(item)'>
              <i class="cuifont icon_rename optionIcon"></i>
            </el-button>
          </div>
        </el-option>
      </el-select>
    </el-tooltip>
    <el-dialog title="Rename"
               width="400px"
               append-to-body
               :close-on-click-modal="false"
               v-if="$attrs.page === 'nextTicketSetting'"
               :visible.sync="dialogFormVisible">
      <el-form :model="renameForm"
               :rules="rules"
               ref="renameForm">
        <el-form-item label="Template Name"
                      prop="name">
          <el-input clearable
                    v-model="renameForm.name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false"
                   size="mini">Cancel</el-button>
        <el-button type="primary"
                   @click="save"
                   size="mini"
                   :loading="renameLoading">Save</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getNextAppInfo } from '@/utils/common'
export default {
  name: 'search-template',
  props: ['nextTicketType', 'timeStamp'],
  data () {
    return {
      currentTemplateId: null,
      oldTemplateId: null,
      dialogFormVisible: false,
      templateOptions: [],
      renameForm: {
        name: '',
      },
      rules: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
        ]
      },
      renameLoading: false
    }
  },
  watch: {
    timeStamp () {
      this.getNextTicketTemplateList()
    },
    currentTemplateId (val, oldVal) {
      this.oldTemplateId = oldVal || null
    },
    '$route.query' () {
      if (this.$route.query.hasOwnProperty('templateId')) {
        const id = Number(this.$route.query.templateId) || null
        this.currentTemplateId = id
        this.changeTemplate(id, 'fun')
      }
    }
  },
  methods: {
    changeTemplate (val, fun) {
      if (fun || this.$attrs.page !== 'nextTicketSetting') {
        let optionItem = this.templateOptions.find(e => e.id === val)
        this.$emit('changeTemplate', { val, optionItem })
      } else {
        this.$confirm(this.$t('custom.nextTicket.loadpleasesave'), this.$t('custom.apps.warning2'), {
          confirmButtonText: this.$t('custom.nextTicket.load'),
          cancelButtonText: this.$t('cancel'),
          dangerouslyUseHTMLString: true
        }).then(() => {
          let optionItem = this.templateOptions.find(e => e.id === val)
          this.$emit('changeTemplate', { val, optionItem })
        }).catch(() => {
          this.currentTemplateId = this.oldTemplateId
        })
      }
    },
    getNextTicketTemplateList (item) {
      const params = {
        type: this.nextTicketType
      }
      this.$interface.nextTicket.getNextTicketTemplateList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data.length >= 0) {
          res.data.unshift({
            name: 'Default Template',
            id: null
          })
          this.templateOptions = res.data
          if (item) {
            if (item.id === this.currentTemplateId) {
              this.currentTemplateId = null
              this.changeTemplate(this.currentTemplateId, 'fun')
            }
            return false
          }
          let isHasTemplate = res.data.find(i => i.checked)
          if (this.$route.query.hasOwnProperty('templateId')) {
            this.currentTemplateId = Number(this.$route.query.templateId) || null
            this.changeTemplate(this.currentTemplateId, 'fun')
            if (this.$attrs.page === 'nextTicketSetting') {
              this.$emit('init', this.currentTemplateId)
            }
          } else if (this.$attrs.currentTemplateId) {
            this.currentTemplateId = this.$attrs.currentTemplateId
            this.changeTemplate(this.currentTemplateId, 'fun')
          } else {
            if (isHasTemplate) {
              this.currentTemplateId = isHasTemplate.id
              this.changeTemplate(this.currentTemplateId, 'fun')
              if (this.$attrs.page === 'nextTicketSetting') {
                this.$emit('init', this.currentTemplateId)
              }
            } else {
              if (this.$attrs.page === 'nextTicketSetting') {
                this.$emit('init')
              }
            }
          }
        }
      }).catch(() => {
      })
    },
    add () {
      this.goRulePage()
    },
    change (item) {
      this.goRulePage(item, 'change')
    },
    changeName (item) {
      this.renameForm = {
        modelId: item.id,
        type: this.nextTicketType,
        name: item.name
      }
      this.dialogFormVisible = true
    },
    save () {
      this.$refs.renameForm.validate(async (valid) => {
        if (valid) {
          const params = {
            ...this.renameForm,
            name: this.renameForm.name.trim()
          }
          const { editRuleName } = this.$interface.apiManager
          this.renameLoading = true
          const { data: res } = await editRuleName(params)
          this.renameLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.code === 0) {
            this.dialogFormVisible = false
            this.$message({
              message: 'Edit Success',
              type: 'success'
            });
            this.getNextTicketTemplateList()
          }
        }
      })
    },
    async clone (item) {
      const params = {
        modelId: item.id,
        type: this.nextTicketType
      }
      const { getTenantRuleListApi } = this.$interface.apiManager
      const { updateTenantRuleApi } = this.$interface.nextTicket
      const { data } = await getTenantRuleListApi(this.$store.state.user.tenantCode, params)
      const templateRuleList = data.data
      const { data: res } = await updateTenantRuleApi(this.$store.state.user.tenantCode, templateRuleList, this.nextTicketType, item.name + ' Copy')
      if (res.code !== 0) {
        this.$message.error(res.msg)
      } else {
        this.$message.success('Success')
        this.getNextTicketTemplateList()
      }
    },
    deleteTemplate (item) {
      this.$confirm('Are you sure to delete?').then(async () => {
        const params = {
          id: item.id,
          type: this.nextTicketType
        }
        this.$interface.nextTicket.delNextTicketTemplate(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$message.success('Success')
            this.getNextTicketTemplateList(item)
          }).catch(() => { })
      })
    },
    goRulePage (item, type) {
      let query = {}
      if (type === 'change') {
        // query.templateId = type ? String(item.id) : null
        query.templateId = item.id
      }
      // switch (this.nextTicketType) {
      //   case 'autotask':
      //     this.$router.push({
      //       path: '/NextTicketForAutotaskPriorityRules',
      //       query
      //     })
      //     break
      //   case 'nextTicket':
      //     this.$router.push({
      //       path: '/NextTicketForConnectWisePriorityRules',
      //       query
      //     })
      //     break
      //   case 'syncro':
      //     this.$router.push({
      //       path: '/NextTicketForSyncroPriorityRules',
      //       query
      //     })
      //     break
      //   case 'kaseyabms':
      //     this.$router.push({
      //       path: '/NextTicketForKaseyaBMSPriorityRules',
      //       query
      //     })
      //     break
      //   default:
      // }
      this.$router.push({
        path: `/NextTicketPriorityRules-${this.nextTicketType}?name=NextTicket For ${getNextAppInfo('resourceId', 'nextTicketName')} Priority Rules`,
        query
      })
      this.$refs['templateSelect'].visible = false
    }
  },
  created () {
    this.getNextTicketTemplateList()
  }
}
</script>

<style scoped lang="scss">
.optionButton {
  float: right;
  font-size: 14px;
  margin-top: 3px;
  margin-left: 10px;
  i {
    font-size: 14px;
    color: #ccc;
  }
}
</style>
